<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Name:  Users Model
*
* Author:  William Bermudo
*
*/

class Users_m extends DataMapperExt
{
	public $table = 'users';
		
	public $has_many = array(
						'blogs' => array(
							'class'			=> 'blog_m',
							'other_field' 	=> 'user',
							'join_self_as'	=> 'author',
							'join_table' 	=> 'posts'
						),
						'posts' => array(
							'class'			=> 'post_m',
							'other_field' 	=> 'user',
							'join_self_as'	=> 'author',
							'join_table' 	=> 'posts'
						),
						
						'subjects'			=> array(
							'class'			=> 'subject_listing_m',
							'other_field'	=> 'teacher',
							'join_self_as'	=> 'teacher',
							'join_other_as'	=> 'subject_listing',
							'join_table'	=> 'teacher_subjects'
						)
						
					);
	
	protected $salt_length = 0;
	protected $store_salt = FALSE;
	
	public function __construct($id = NULL)
	{
		parent::__construct($id);
		$this->config->load('users/auth', TRUE);
		$this->tables  = $this->config->item('tables', 'auth');
		$table = $this->tables['users'];
		
		// Get Salt Length
		$this->enc = $this->config->item('encryption', 'auth');
		$this->salt_length = $this->enc['salt_length'];
		$this->store_salt = $this->enc['store_salt'];
	}
	
	public function salt()
	{
		return substr(md5(uniqid(rand(), true)), 0, $this->salt_length);
	}
	
	public function hash_password($password, $salt = FALSE)
	{
		if (empty($password))
		{
			return FALSE;
		}
		
		return sha1($password . $salt);
	}
	
	public function hash_password_db($identity, $password)
	{
		$u = new Users_m();
		
		$u->select('password')
		  ->select('salt')
		  ->where('email', $identity)
		  ->limit(1);
		
		$u->get();
			
		if ($u->result_count() !== 1)
		{
			return FALSE;
		}
		
		if ($this->store_salt)
		{
			return sha1($password . $u->salt);
		}
	}
	
	public function login($identity, $password)
	{
		if (empty($identity) || empty($password))
		{
			return FALSE;
		}
		
		$u = new Users_m();
		
		$u->select('id, email, password, role_id')
		  ->where('email', $identity)
		  ->where('is_active', '1');
		  
		$u->get();
		
		if ($u->result_count() == 0)
        {
            // Login failed
            return FALSE;
        }
        else
        {
			// Random create new salt
			$salt				= $this->store_salt ? $this->salt() : FALSE;
			$salted_password 	= $this->hash_password($password, $salt);
			
			$password = $this->hash_password_db($identity, $password);
			
			if ($password == $u->password)
			{
				// Login succeeded
				$user_data = array(
								   'id'		   => $u->id,	
								   'username'  => $u->username,
							       'email'     => $u->email,
								   'logged_in' => TRUE
				);
				
				$this->session->set_userdata($user_data);
				
				$this->update_password($salted_password, $salt);
				$this->update_last_login();
				
				return TRUE;
			}
        }
	}
	
	public function update_password($password, $salt)
	{
		$u = new Users_m();
		
		$user_data = array();
		$user_data['password']  = $password;
		$user_data['salt']		= $salt;
		
		$u->where('id', $this->session->userdata('id'))
		  ->update($user_data);
	}
	
	public function update_last_login()
	{
		$u = new Users_m();
		
		$u->where('id', $this->session->userdata('id'))
			->update('date_last_modified', now());
	}
	
	public function get_user($id)
	{
		$u = new Users_m();
		
		$user_data = array(
							'id' => $id
						  );
		
		$u->get_where($user_data, 1);
		
		if ($u->result_count() > 0)
		{
			$user_data = array(
					'id'		=> $u->id,
					'username' 	=> $u->username,
					'email'		=> $u->email
			);
			
			return $user_data;
		}
		
		return FALSE;
	}
	
	public function create_user($user_data)
	{
		$objUser = new Users_m();
		
		foreach ($user_data as $key => $value)
		{
			if ($key == 'password')
			{
				$salt		= $this->store_salt ? $this->salt() : FALSE;
				$password	= $this->hash_password($value, $salt);
				$objUser->$key = $password;
			}
			else
			{
				$objUser->$key = $value;
			}
		}
		
		if ($this->store_salt)
		{
			$objUser->salt = $salt;
		}
		
		$objUser->save();
		
		$id = $objUser->id;
		
		if ($id)
		{
			return $id;
		}
		
		return NULL;
	}
	
	public function check_username($username)
	{
		$objUser = new Users_m();
		
		$objUser->where('username', $username);
		
		$objUser->get();
		
		if ($objUser->result_count() > 0)
		{
			return TRUE;
		}
		
		return FALSE;
	}
	
	public function check_email($email)
	{
		$objUser = new Users_m();
		
		$objUser->where('email', $email);
		
		$objUser->get();
		
		if ($objUser->result_count() > 0)
		{
			return TRUE;
		}
		
		return FALSE;
	}
}